﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.ObjectPool;
using System.ServiceModel.Channels;
using System.ServiceModel;
using Framework.Entity;

namespace Framework.ObjectFactory
{
    public static class ServiceFactory<TInterface> where TInterface : class, IService
    {
        private static Dictionary<Type, IService> dicTypeServiceCollection = new Dictionary<Type, IService>();
        private static object lockObj = new object();

        public static TInterface GetInstance()
        {
            Type type = typeof(TInterface);
            IService service = null;
            if (!dicTypeServiceCollection.TryGetValue(type, out service))
            {
                lock (lockObj)
                {
                    if (!dicTypeServiceCollection.TryGetValue(type, out service))
                    {
                        NetMsmqBinding binding = new NetMsmqBinding(NetMsmqSecurityMode.None);// new BasicHttpBinding();// todo:
                        binding.TimeToLive = new TimeSpan(0, 0, 30);
                        binding.DeadLetterQueue = DeadLetterQueue.Custom;
                        binding.CustomDeadLetterQueue = new Uri("net.msmq://localhost/private/customDLQ");
                        EndpointAddress address = new EndpointAddress("net.msmq://localhost/private/myservice");// todo:
                        Type typeProxy = ProxyBuilder.BuildType<TInterface, ChannelFactoryClassBuilder<TInterface>>();
                        service = (TInterface)Activator.CreateInstance(typeProxy, binding, address);
                        dicTypeServiceCollection[type] = service;
                    }
                }
            }

            return (TInterface)service;
        }
    }
}
